package com.hyt.it.ogt.ykcj.service.grade.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hyt.exception.exception.BusinessLogicException;
import com.hyt.it.ogt.common.config.GlobalConfig;
import com.hyt.it.ogt.ykcj.common.core.domain.entity.SysDictData;
import com.hyt.it.ogt.ykcj.common.enums.CommonEnums;
import com.hyt.it.ogt.ykcj.common.enums.ExamResultDownLoadFileTypeEnum;
import com.hyt.it.ogt.ykcj.domain.exam.ExamInfo;
import com.hyt.it.ogt.ykcj.domain.exam.ExamNameConfig;
import com.hyt.it.ogt.ykcj.domain.exam.ExamSubjectInfo;
import com.hyt.it.ogt.ykcj.domain.exam.ExamSubjectNameConfig;
import com.hyt.it.ogt.ykcj.domain.grade.EnterpriseExamineeInfo;
import com.hyt.it.ogt.ykcj.domain.param.EnterpriseScoreLineSaveParam;
import com.hyt.it.ogt.ykcj.domain.param.ScoreLineItem;
import com.hyt.it.ogt.ykcj.domain.vo.*;
import com.hyt.it.ogt.ykcj.domain.vo.export.ExportEnterpriseExamineeScoreVo;
import com.hyt.it.ogt.ykcj.domain.vo.export.ExportEnterpriseExamineeStemScoreVo;
import com.hyt.it.ogt.ykcj.domain.vo.export.ExportEnterpriseExamineeSubjectGradeScoreVo;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamNameConfigMapper;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamSubjectInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.exam.ExamSubjectNameConfigMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeInfoMapper;
import com.hyt.it.ogt.ykcj.mapper.grade.EnterpriseExamineeSubjectGradeMapper;
import com.hyt.it.ogt.ykcj.mapper.system.SysDictDataMapper;
import com.hyt.it.ogt.ykcj.service.exam.IClassificationService;
import com.hyt.it.ogt.ykcj.service.exam.IEnterpriseExamScoreLineSettingService;
import com.hyt.it.ogt.ykcj.service.exam.IExamResultDataDownLoadRecordService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseExamineeGradeExportService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseExamineeInfoService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseGroupExamineeInfoService;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.service.IBaseLoginService;
import com.hyt.progress.service.ProgressManager;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 考试组考生信息Service业务层处理
 *
 * @author liying
 * @date 2021-11-19
 */
@Service
public class EnterpriseGroupExamineeInfoServiceImpl implements IEnterpriseGroupExamineeInfoService {
    private static final Logger log = LoggerFactory.getLogger(EnterpriseGroupExamineeInfoServiceImpl.class);

    @Autowired
    private EnterpriseExamineeSubjectGradeMapper enterpriseExamineeSubjectGradeMapper;

    @Autowired
    private ExamInfoMapper examInfoMapper;

    @Autowired
    private IBaseLoginService iBaseLoginService;

    @Autowired
    private IEnterpriseExamineeInfoService enterpriseExamineeInfoService;

    @Autowired
    private ExamNameConfigMapper examNameConfigMapper;

    @Autowired
    private IClassificationService classificationService;

    @Autowired
    private IExamResultDataDownLoadRecordService examResultDataDownLoadRecordService;

    @Autowired
    private EnterpriseExamineeInfoExportUtil enterpriseExamineeInfoExportUtil;

    @Resource
    GlobalConfig globalConfig;

    @Autowired
    private SysDictDataMapper selectDictDataMap;

    @Autowired
    private ExamSubjectInfoMapper examSubjectInfoMapper;

    @Autowired
    private EnterpriseExamineeInfoMapper enterpriseExamineeInfoMapper;

    @Autowired
    private IEnterpriseExamScoreLineSettingService enterpriseExamScoreLineSettingService;

    @Autowired
    private IEnterpriseExamineeGradeExportService enterpriseExamineeGradeExportService;

    @Autowired
    private ExamSubjectNameConfigMapper examSubjectNameConfigMapper;

    /**
     * 分页查询企业招聘考生信息列表
     *
     * @param queryExamineeVo
     * @return
     */
    @Override
    public PageInfo<List<EnterpriseExamineeInfoVo>> selectEnterpriseExamineeGradePage(QueryEnterpriseExamineeGradeVo queryExamineeVo) {
        //筛选子考试
        if (StringUtils.isNotEmpty(queryExamineeVo.getRelationExamId())) {
            queryExamineeVo.setExamId(queryExamineeVo.getRelationExamId());
        }
        ExamInfo examInfo = examInfoMapper.selectExamInfoById(queryExamineeVo.getExamId());
        if (null == examInfo) {
            return new PageInfo(Collections.emptyList());
        }
        queryExamineeVo.setOfficeId(iBaseLoginService.getOfficeId());
        //合并考试的考试组
        if (null != examInfo.getMergeType() && CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))) {
            //关联考试的考试组
            Map<String, Object> parms = new HashMap<>();
            parms.put("relationId", examInfo.getId());
            List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
            List<String> examIds = examInfoVos.stream().map(e -> e.getId()).collect(Collectors.toList());
            queryExamineeVo.setExamIds(examIds.toArray(new String[examIds.size()]));
            queryExamineeVo.setExamId(null);
            PageHelper.startPage(queryExamineeVo.getPageNum(), queryExamineeVo.getPageSize());
            List<EnterpriseExamineeInfoVo> enterpriseExamineeInfoVos = enterpriseExamineeInfoService.selectGroupEnterpriseExamineeGradePage(queryExamineeVo);
            if (CollectionUtils.isEmpty(enterpriseExamineeInfoVos)) {
                return new PageInfo(Collections.emptyList());
            }
            Set<String> eaxmIds = examInfoVos.stream().map(e -> e.getId()).collect(Collectors.toSet());
            Set<String> names = enterpriseExamineeInfoVos.stream().filter(e -> StringUtils.isNotEmpty(e.getName())).map(e -> e.getName()).collect(Collectors.toSet());
            Set<String> idCards = enterpriseExamineeInfoVos.stream().filter(e -> StringUtils.isNotEmpty(e.getIdcard())).map(e -> e.getIdcard()).collect(Collectors.toSet());
            String[] arrayEaxmIds = eaxmIds.toArray(new String[eaxmIds.size()]);
            String[] arrayNames = names.toArray(new String[names.size()]);
            String[] arrayIdCards = idCards.toArray(new String[idCards.size()]);
            Map<String, Object> examineeParms = new HashMap<>();
            examineeParms.put("examIds", arrayEaxmIds);
            examineeParms.put("names", arrayNames);
            examineeParms.put("idcards", arrayIdCards);
            List<EnterpriseExamineeExamGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper
                    .selectEnterpriseExamineeByParms(examineeParms);


            if (CollectionUtils.isEmpty(enterpriseExamineeSubjectGradeVos)) {
                return new PageInfo(enterpriseExamineeInfoVos);
            }
            //赋值考试名称
            Map<String, String> examNameMap = examInfoVos.stream().collect(Collectors.toMap(ExamInfoVo::getId, ExamInfoVo::getExamNameConfigName, (key1, key2) -> key2));
            for (EnterpriseExamineeExamGradeVo subjectGradeVo : enterpriseExamineeSubjectGradeVos) {
                if (MapUtils.isNotEmpty(examNameMap) && null != examNameMap.get(subjectGradeVo.getExamId())) {
                    subjectGradeVo.setExamName(examNameMap.get(subjectGradeVo.getExamId()));
                }
            }
            //总成绩 key name + idcard
            Map<String, List<EnterpriseExamineeExamGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getName() + c.getIdCard()));
            for (EnterpriseExamineeInfoVo vo : enterpriseExamineeInfoVos) {
                if (MapUtils.isEmpty(subjectGradeMap) || null == subjectGradeMap.get(vo.getName() + vo.getIdcard())) {
                    continue;
                }
                //存在多场考试根据examId分组
                List<EnterpriseExamineeExamGradeVo> examList = subjectGradeMap.get(vo.getName() + vo.getIdcard());
                //考试组总分
                vo.setScore(examList.stream().map(EnterpriseExamineeExamGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
                Map<String, List<EnterpriseExamineeExamGradeVo>> examGradeMap = examList.stream().collect(Collectors.groupingBy(c -> c.getExamId()));
                List<EnterpriseExamineeSubjectGradeVo> gradeList = new ArrayList<>(1);
                for (String key : examGradeMap.keySet()) {
                    EnterpriseExamineeSubjectGradeVo subjectGradeVo = new EnterpriseExamineeSubjectGradeVo();
                    subjectGradeVo.setScore(examGradeMap.get(key).stream().map(EnterpriseExamineeExamGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
                    //已经按照考试分组了，则只需要取一次考试就行
                    subjectGradeVo.setSubjectId(examGradeMap.get(key).get(0).getExamId());
                    subjectGradeVo.setExamId(examGradeMap.get(key).get(0).getExamId());
                    subjectGradeVo.setSubjectName(examGradeMap.get(key).get(0).getExamName());
                    gradeList.add(subjectGradeVo);

                }
                vo.setGradeList(gradeList);
            }

            return new PageInfo(enterpriseExamineeInfoVos);
            //合并科目的考试组
        } else {
            queryExamineeVo.setExamId(examInfo.getId());
            return enterpriseExamineeInfoService.selectEnterpriseExamineeGradePage(queryExamineeVo);
        }

    }


    @Override
    public void exportExcelByCondition(QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo, User user, ExamResultDownLoadFileTypeEnum fileType) throws Exception {
        // 判断考试是否存在
        ExamInfo examInfo = examInfoMapper.selectExamInfoById(queryEnterpriseExamineeGradeVo.getExamId());
        if (examInfo == null || StringUtils.isEmpty(examInfo.getExamNameConfigId())) {
            BusinessLogicException.throwException(52293104, "所选考试不存在");
        }
        //合并考试
        if (CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(examInfo.getMergeType()))) {
            if (StringUtils.isNotEmpty(queryEnterpriseExamineeGradeVo.getRelationExamId())) {
                //合并考试，导出子考试成绩
                queryEnterpriseExamineeGradeVo.setExamId(queryEnterpriseExamineeGradeVo.getRelationExamId());
                enterpriseExamineeGradeExportService.exportExcelByCondition(queryEnterpriseExamineeGradeVo, user, fileType);
            } else {
                //合并考试，导出总成绩
                exportGroupExamExcel(examInfo, queryEnterpriseExamineeGradeVo, user, fileType);
            }
        } else {
            if (StringUtils.isNotEmpty(queryEnterpriseExamineeGradeVo.getSubjectId())) {
                //合并科目，导出科目成绩
                exportSubjectExcelByCondition(examInfo, queryEnterpriseExamineeGradeVo, user, fileType);
            } else {
                //合并科目，导出总成绩
                exportCommonExcelByCondition(examInfo, queryEnterpriseExamineeGradeVo, user, fileType);
            }
        }
    }


    private void exportGroupExamExcel(ExamInfo examInfo, QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo,
                                      User user, ExamResultDownLoadFileTypeEnum fileType) throws Exception {
        String examNameConfigId = examInfo.getExamNameConfigId();
        ExamNameConfig examNameConfig = examNameConfigMapper.selectExamNameConfigById(examNameConfigId);
        if (examNameConfig == null || StringUtils.isEmpty(examNameConfig.getName())) {
            BusinessLogicException.throwException(52293203, "所选考试名称配置信息不存在");
        }
        ProgressManager.updateProgressCurrent(5, "获取考试名称配置信息完成");

        // zip文件URL
        String dbfUrl = null;
        try {
            // 设置导出时候的名称
            queryEnterpriseExamineeGradeVo.setFileName(System.currentTimeMillis() + "_" + examNameConfig.getName() + "_" + "成绩");
            queryEnterpriseExamineeGradeVo.setSheetName(examNameConfig.getName() + "成绩列表");
            //查询考试组下面的子考试名称
            // 一：（查询表格头）获取考试的科目,存在查询不到学生信息的情况，用这个考试科目的内容来构建excel的列的表头
            Map<String, Object> parms = new HashMap<>();
            parms.put("relationId", queryEnterpriseExamineeGradeVo.getExamId());
            List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
            if (CollectionUtils.isEmpty(examInfoVos)) {
                BusinessLogicException.throwException(52293204, "所选考试不存在考生数据");
            }
            ProgressManager.updateProgressCurrent(15, "获取所选考试信息完成");

            List<String> eaxmIds = examInfoVos.stream().distinct().map(e -> e.getId()).collect(Collectors.toList());
            List<ExportEnterpriseExamineeSubjectGradeScoreVo> subjectList = getSubjectList(eaxmIds, examInfoVos, CommonEnums.EXAM_MERGE_TYPE_0.getCode());
            ProgressManager.updateProgressCurrent(20, "获取科目列表完成");

            // 二：（查询表格内容）如果传了考生id：则导出考生的考试题干成绩 ； 如果没传考生id：则导出该场考试的全部学生的考试题干成绩
            //关联考试组列表只存在其中一场考试考生的id，需要把其他考试的考生id也查出来
            List<ExportEnterpriseExamineeScoreVo> enterpriseExamineeScoreVos = null;
            if (null != queryEnterpriseExamineeGradeVo.getExamineeIds() && queryEnterpriseExamineeGradeVo.getExamineeIds().length > 0) {
                List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoService.selectEnterpriseExamineeInfoByIds(Arrays.asList(queryEnterpriseExamineeGradeVo.getExamineeIds()));
                ProgressManager.updateProgressCurrent(25, "获取考生列表完成");

                //查询出考生的科目成绩
                Set<String> names = enterpriseExamineeInfos.stream().filter(e -> StringUtils.isNotEmpty(e.getName())).map(e -> e.getName()).collect(Collectors.toSet());
                Set<String> idCards = enterpriseExamineeInfos.stream().filter(e -> StringUtils.isNotEmpty(e.getIdcard())).map(e -> e.getIdcard()).collect(Collectors.toSet());
                String[] arrayEaxmIds = eaxmIds.toArray(new String[eaxmIds.size()]);
                String[] arrayNames = names.toArray(new String[names.size()]);
                String[] arrayIdCards = idCards.toArray(new String[idCards.size()]);
                Map<String, Object> examineeParms = new HashMap<>();
                examineeParms.put("deptIds", queryEnterpriseExamineeGradeVo.getDeptIds());
                examineeParms.put("examIds", arrayEaxmIds);
                examineeParms.put("names", arrayNames);
                examineeParms.put("idcards", arrayIdCards);
                examineeParms.put("groupQualifiedStatus", queryEnterpriseExamineeGradeVo.getQualifiedStatus());
                examineeParms.put("archivedGroupStatus", queryEnterpriseExamineeGradeVo.getArchivedStatus());
                examineeParms.put("groupRegionName", queryEnterpriseExamineeGradeVo.getRegionName());
                examineeParms.put("examineeName", queryEnterpriseExamineeGradeVo.getExamineeName());
                List<EnterpriseExamineeExamGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeByParms(examineeParms);
                //总成绩 key name + idcard
                Map<String, List<EnterpriseExamineeExamGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getName() + c.getIdCard()));
                enterpriseExamineeScoreVos = getExportEnterpriseExamineeScoreVos(subjectGradeMap, CommonEnums.EXAM_MERGE_TYPE_0.getCode());
            } else {
                //查询出考生的科目成绩
                String[] arrayEaxmIds = eaxmIds.toArray(new String[eaxmIds.size()]);
                Map<String, Object> examineeParms = new HashMap<>();
                examineeParms.put("deptIds", queryEnterpriseExamineeGradeVo.getDeptIds());
                examineeParms.put("examIds", arrayEaxmIds);
                examineeParms.put("names", null);
                examineeParms.put("idcards", null);
                examineeParms.put("groupQualifiedStatus", queryEnterpriseExamineeGradeVo.getQualifiedStatus());
                examineeParms.put("archivedGroupStatus", queryEnterpriseExamineeGradeVo.getArchivedStatus());
                examineeParms.put("groupRegionName", queryEnterpriseExamineeGradeVo.getRegionName());
                examineeParms.put("examineeName", queryEnterpriseExamineeGradeVo.getExamineeName());
                List<EnterpriseExamineeExamGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeByParms(examineeParms);
                //总成绩 key name + idcard
                Map<String, List<EnterpriseExamineeExamGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getName() + c.getIdCard()));
                enterpriseExamineeScoreVos = getExportEnterpriseExamineeScoreVos(subjectGradeMap, CommonEnums.EXAM_MERGE_TYPE_0.getCode());
                //缺少子考试集合数据
            }
            ProgressManager.updateProgressCurrent(40, "获取考生数据完成");

            // 5：设置学历、性别
            bulidEducationAndSex(enterpriseExamineeScoreVos);
            ProgressManager.updateProgressCurrent(45, "设置学历、性别完成");

            XSSFWorkbook xssfWorkbook = EnterpriseExamineeInfoExportUtil.getExamineeExamXSSFWorkbook(enterpriseExamineeScoreVos, subjectList, queryEnterpriseExamineeGradeVo.getSheetName());
            ProgressManager.updateProgressCurrent(50, "Excel文件生成完成");

            dbfUrl = enterpriseExamineeInfoExportUtil.exportExcelV2(xssfWorkbook, queryEnterpriseExamineeGradeVo.getFileName());
            ProgressManager.updateProgressCurrent(55, "文件上传华为云完成");
        } catch (Exception e) {
            log.error("# 23、上传{}文件异常", queryEnterpriseExamineeGradeVo.getFileName(), e);
        }

        if (StringUtils.isEmpty(dbfUrl)) {
            BusinessLogicException.throwException(52293106, "文件生成失败");
        }
        ProgressManager.finish(dbfUrl);
    }


    private List<ExportEnterpriseExamineeSubjectGradeScoreVo> getSubjectList(List<String> eaxmIds, List<ExamInfoVo> examInfoVos, String mergeType) {
        List<ExportEnterpriseExamineeSubjectGradeScoreVo> subjectList = new ArrayList<>();
        List<ExamSubjectVo> examSubjectVos = examSubjectInfoMapper.selectExamSubjectInfoByExamIds(eaxmIds.toArray(new String[eaxmIds.size()]));
        Map<String, List<ExamSubjectVo>> examSubjectMap = examSubjectVos.stream().collect(Collectors.groupingBy(c -> c.getExamInfoId()));
        if (CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(mergeType)) {
            for (ExamInfoVo examInfoVo : examInfoVos) {
                ExportEnterpriseExamineeSubjectGradeScoreVo vo = new ExportEnterpriseExamineeSubjectGradeScoreVo();
                vo.setSubjectName(examInfoVo.getExamNameConfigName());
                vo.setSubjectId(examInfoVo.getId());
                if (MapUtils.isNotEmpty(examSubjectMap) && CollectionUtils.isNotEmpty(examSubjectMap.get(examInfoVo.getId()))) {
                    List<ExamSubjectVo> subjectInfos = examSubjectMap.get(examInfoVo.getId());
                    List<ExportEnterpriseExamineeStemScoreVo> stemScoreVos = new ArrayList<>(subjectInfos.size());
                    for (ExamSubjectVo subjectInfo : subjectInfos) {
                        ExportEnterpriseExamineeStemScoreVo stemScoreVo = new ExportEnterpriseExamineeStemScoreVo();
                        stemScoreVo.setStemId(subjectInfo.getSubjectId());
                        stemScoreVo.setStemName(subjectInfo.getSubjectName());
                        stemScoreVos.add(stemScoreVo);
                    }
                    vo.setExportEnterpriseExamineeStemScoreVos(stemScoreVos);
                }

                subjectList.add(vo);
            }
        } else {
            for (ExamSubjectVo examSubjectVo : examSubjectVos) {
                ExportEnterpriseExamineeSubjectGradeScoreVo vo = new ExportEnterpriseExamineeSubjectGradeScoreVo();
                vo.setSubjectName(examSubjectVo.getSubjectName());
                vo.setSubjectId(examSubjectVo.getSubjectId());
                subjectList.add(vo);
            }
        }

        return subjectList;
    }

    private List<ExportEnterpriseExamineeScoreVo> getExportEnterpriseExamineeScoreVos(Map<String, List<EnterpriseExamineeExamGradeVo>> subjectGradeMap, String mergeType) {
        List<ExportEnterpriseExamineeScoreVo> enterpriseExamineeScoreVos = new ArrayList<>();
        for (String key : subjectGradeMap.keySet()) {
            List<EnterpriseExamineeExamGradeVo> enterpriseExamineeExamGradeVos = subjectGradeMap.get(key);
            if (CollectionUtils.isEmpty(enterpriseExamineeExamGradeVos)) {
                continue;
            }
            EnterpriseExamineeExamGradeVo vo = enterpriseExamineeExamGradeVos.get(0);
            ExportEnterpriseExamineeScoreVo exportEnterpriseExamineeScoreVo = new ExportEnterpriseExamineeScoreVo();
            if (CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(mergeType)) {
                if (CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(vo.getGroupQualifiedStatus())) {
                    exportEnterpriseExamineeScoreVo.setQualifiedStatus(CommonEnums.QUALIFIED_STATUS_Y.getDesc());
                } else if (CommonEnums.QUALIFIED_STATUS_N.getCode().equals(vo.getGroupQualifiedStatus())) {
                    exportEnterpriseExamineeScoreVo.setQualifiedStatus(CommonEnums.QUALIFIED_STATUS_N.getDesc());
                } else {
                    exportEnterpriseExamineeScoreVo.setQualifiedStatus("--");
                }
                if (StringUtils.isNotEmpty(vo.getGroupRegionName())) {
                    exportEnterpriseExamineeScoreVo.setQualifiedStatus(vo.getGroupRegionName());
                }
                exportEnterpriseExamineeScoreVo.setRegionName(vo.getGroupRegionName());

            } else {
                if (CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(vo.getQualifiedStatus())) {
                    exportEnterpriseExamineeScoreVo.setQualifiedStatus(CommonEnums.QUALIFIED_STATUS_Y.getDesc());
                } else if (CommonEnums.QUALIFIED_STATUS_N.getCode().equals(vo.getQualifiedStatus())) {
                    exportEnterpriseExamineeScoreVo.setQualifiedStatus(CommonEnums.QUALIFIED_STATUS_N.getDesc());
                } else {
                    exportEnterpriseExamineeScoreVo.setQualifiedStatus("--");
                }
                if (StringUtils.isNotEmpty(vo.getRegionName())) {
                    exportEnterpriseExamineeScoreVo.setQualifiedStatus(vo.getRegionName());
                }
                exportEnterpriseExamineeScoreVo.setRegionName(vo.getRegionName());

            }


            exportEnterpriseExamineeScoreVo.setEducation(vo.getEducation());
            exportEnterpriseExamineeScoreVo.setSex(vo.getSex());
            exportEnterpriseExamineeScoreVo.setTotalScore((enterpriseExamineeExamGradeVos.stream().map(EnterpriseExamineeExamGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add)));
            exportEnterpriseExamineeScoreVo.setAdmissionNo(vo.getAdmissionNo());
            exportEnterpriseExamineeScoreVo.setId(vo.getExamineeId());
            exportEnterpriseExamineeScoreVo.setIdcard(vo.getIdCard());
            exportEnterpriseExamineeScoreVo.setMobile(vo.getMobile());
            exportEnterpriseExamineeScoreVo.setName(vo.getName());

            //查询考试所有的科目
            Map<String, List<EnterpriseExamineeExamGradeVo>> subjectMap = enterpriseExamineeExamGradeVos.stream().filter(e -> StringUtils.isNotEmpty(e.getExamId())).collect(Collectors.groupingBy(c -> c.getExamId()));

            if (CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(mergeType)) {
                //考了全部的子考试
                List<ExportEnterpriseExamineeSubjectGradeScoreVo> gradeScoreVos = new ArrayList<>(enterpriseExamineeExamGradeVos.size());
                for (String key1 : subjectMap.keySet()) {
                    List<EnterpriseExamineeExamGradeVo> examGradeVos = subjectMap.get(key1);
                    ExportEnterpriseExamineeSubjectGradeScoreVo gradeScoreVo = new ExportEnterpriseExamineeSubjectGradeScoreVo();
                    gradeScoreVo.setSubjectId(key1);

//                if (MapUtils.isNotEmpty(subjectMap) && CollectionUtils.isNotEmpty(subjectMap.get(examGradeVo.getExamId()))) {

                    gradeScoreVo.setSubjectScore(examGradeVos.stream().map(EnterpriseExamineeExamGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add));
                    List<ExportEnterpriseExamineeStemScoreVo> stemScoreVos = new ArrayList<>(examGradeVos.size());
                    for (EnterpriseExamineeExamGradeVo examineeExamGradeVo : examGradeVos) {
                        ExportEnterpriseExamineeStemScoreVo stemScoreVo = new ExportEnterpriseExamineeStemScoreVo();
                        stemScoreVo.setStemId(examineeExamGradeVo.getSubjectId());
                        stemScoreVo.setStemScore(examineeExamGradeVo.getScore());
                        stemScoreVos.add(stemScoreVo);
                    }
                    gradeScoreVo.setExportEnterpriseExamineeStemScoreVos(stemScoreVos);
//                }
                    gradeScoreVos.add(gradeScoreVo);
                }
                exportEnterpriseExamineeScoreVo.setExportEnterpriseExamineeSubjectGradeScoreVos(gradeScoreVos);
                enterpriseExamineeScoreVos.add(exportEnterpriseExamineeScoreVo);
            } else {
                //考了全部的科目
                List<ExportEnterpriseExamineeSubjectGradeScoreVo> gradeScoreVos = new ArrayList<>(enterpriseExamineeExamGradeVos.size());
                for (EnterpriseExamineeExamGradeVo examGradeVo : enterpriseExamineeExamGradeVos) {
                    ExportEnterpriseExamineeSubjectGradeScoreVo gradeScoreVo = new ExportEnterpriseExamineeSubjectGradeScoreVo();
                    gradeScoreVo.setSubjectId(examGradeVo.getSubjectId());
                    gradeScoreVo.setSubjectScore(examGradeVo.getScore());
//                    gradeScoreVo.setQualifiedStatus(exportEnterpriseExamineeScoreVo.getQualifiedStatus());
                    gradeScoreVos.add(gradeScoreVo);
                }
                exportEnterpriseExamineeScoreVo.setExportEnterpriseExamineeSubjectGradeScoreVos(gradeScoreVos);
                enterpriseExamineeScoreVos.add(exportEnterpriseExamineeScoreVo);
            }

        }
        return enterpriseExamineeScoreVos;
    }

    private void bulidEducationAndSex(List<ExportEnterpriseExamineeScoreVo> enterpriseExamineeScoreVos) {
        SysDictData dictData = new SysDictData();
        dictData.setDictType("education");
        List<SysDictData> educationDicList = selectDictDataMap.selectDictDataList(dictData);
        dictData.setDictType("sys_user_sex");
        List<SysDictData> sexDicList = selectDictDataMap.selectDictDataList(dictData);
        for (ExportEnterpriseExamineeScoreVo enterpriseExamineeScoreVo : enterpriseExamineeScoreVos) {
            {
                educationDicList.stream().forEach(sysDictData -> {
                    if (sysDictData.getDictValue().equals(enterpriseExamineeScoreVo.getEducation())) {
                        enterpriseExamineeScoreVo.setEducation(sysDictData.getDictLabel());
                        return;
                    }
                });
                sexDicList.stream().forEach(sexDictData -> {
                    if (sexDictData.getDictValue().equals(enterpriseExamineeScoreVo.getSex())) {
                        enterpriseExamineeScoreVo.setSex(sexDictData.getDictLabel());
                        return;
                    }
                });
            }
        }
    }

    public void exportCommonExcelByCondition(ExamInfo examInfo, QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo, User user, ExamResultDownLoadFileTypeEnum fileType) throws Exception {
        String examNameConfigId = examInfo.getExamNameConfigId();
        ExamNameConfig examNameConfig = examNameConfigMapper.selectExamNameConfigById(examNameConfigId);
        if (examNameConfig == null || StringUtils.isEmpty(examNameConfig.getName())) {
            BusinessLogicException.throwException(52293205, "所选考试名称配置信息不存在");
        }
        ProgressManager.updateProgressCurrent(10, "获取考试名称配置完成");

        // zip文件URL
        String dbfUrl = null;
        try {
            // 设置导出时候的名称
            queryEnterpriseExamineeGradeVo.setFileName(System.currentTimeMillis() + "_" + examNameConfig.getName() + "_" + "成绩");
            queryEnterpriseExamineeGradeVo.setSheetName(examNameConfig.getName() + "成绩列表");
            // 一：（查询表格头）获取考试的科目,存在查询不到学生信息的情况，用这个考试科目的内容来构建excel的列的表头
            Map<String, Object> parms = new HashMap<>();
            parms.put("id", examInfo.getId());
            List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
            ProgressManager.updateProgressCurrent(20, "获取考试信息完成");

            List<String> eaxmIds = new ArrayList<>(1);
            eaxmIds.add(queryEnterpriseExamineeGradeVo.getExamId());
            List<ExportEnterpriseExamineeSubjectGradeScoreVo> subjectList = getSubjectList(eaxmIds, examInfoVos, CommonEnums.EXAM_MERGE_TYPE_1.getCode());
            ProgressManager.updateProgressCurrent(30, "获取导出科目完成");

            // 二：（查询表格内容）如果传了考生id：则导出考生的考试题干成绩 ； 如果没传考生id：
            List<ExportEnterpriseExamineeScoreVo> enterpriseExamineeScoreVos = getExportEnterpriseExamineeScoreVos(queryEnterpriseExamineeGradeVo);
            ProgressManager.updateProgressCurrent(40, "获取导出表格内容完成");

            // 传了区间则做筛选
            if (StrUtil.isNotEmpty(queryEnterpriseExamineeGradeVo.getRegionName())) {
                enterpriseExamineeScoreVos = enterpriseExamineeScoreVos.stream().filter(item -> queryEnterpriseExamineeGradeVo.getRegionName().equals(item.getRegionName())).collect(Collectors.toList());
            }

            // 5：设置学历、性别
            bulidEducationAndSex(enterpriseExamineeScoreVos);
            ProgressManager.updateProgressCurrent(50, "设置学历、性别完成");

            XSSFWorkbook xssfWorkbook = EnterpriseExamineeInfoExportUtil.getExamineeSubjectXSSFWorkbook(enterpriseExamineeScoreVos, subjectList, queryEnterpriseExamineeGradeVo.getSheetName());
            ProgressManager.updateProgressCurrent(60, "数据写入Excel完成");

            dbfUrl = enterpriseExamineeInfoExportUtil.exportExcelV2(xssfWorkbook, queryEnterpriseExamineeGradeVo.getFileName());
            ProgressManager.updateProgressCurrent(70, "文件上传华为云完成");
        } catch (Exception e) {
            log.error("# 23、上传{}文件异常", queryEnterpriseExamineeGradeVo.getFileName(), e);
        }

        if (StringUtils.isEmpty(dbfUrl)) {
            BusinessLogicException.throwException(52293106, "文件生成失败");
        }
        ProgressManager.finish(dbfUrl);
    }


    public void exportSubjectExcelByCondition(ExamInfo examInfo, QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo, User user, ExamResultDownLoadFileTypeEnum fileType) throws Exception {
        // zip文件URL
        String dbfUrl = null;
        try {
            //判断考试是否存在
            ExamSubjectInfo examSubjectInfo = examSubjectInfoMapper.selectExamSubjectInfoById(queryEnterpriseExamineeGradeVo.getSubjectId());
            if (examSubjectInfo == null || org.springframework.util.StringUtils.isEmpty(examSubjectInfo.getExamInfoId())) {
                BusinessLogicException.throwException(52293105, "所选科目不存在");
            }
            ProgressManager.updateProgressCurrent(10, "获取考试科目信息完成");

            //设置导出时候的名称
            ExamSubjectNameConfig examSubjectNameConfig = examSubjectNameConfigMapper.selectExamSubjectNameConfigById(examSubjectInfo.getExamSubjectNameId());
            ProgressManager.updateProgressCurrent(20, "获取导出文件名称完成");

            queryEnterpriseExamineeGradeVo.setFileName(examSubjectNameConfig.getName() + "成绩");
            queryEnterpriseExamineeGradeVo.setSheetName(examSubjectNameConfig.getName() + "成绩列表");
            //一：（查询表格头）获取考试的科目,存在查询不到学生信息的情况，用这个考试科目的内容来构建excel的列的表头
            List<String> eaxmIds = new ArrayList<>(1);
            eaxmIds.add(queryEnterpriseExamineeGradeVo.getExamId());
            Map<String, Object> parms = new HashMap<>();
            parms.put("id", examInfo.getId());
            List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
            ProgressManager.updateProgressCurrent(30, "获取考试信息完成");

            List<ExportEnterpriseExamineeSubjectGradeScoreVo> subjectList = getSubjectList(eaxmIds, examInfoVos, CommonEnums.EXAM_MERGE_TYPE_1.getCode());
            ProgressManager.updateProgressCurrent(40, "获取考试科目完成");

            //二：（查询表格内容）如果传了考生id：则导出考生的考试题干成绩  ； 如果没传考生id：则导出该场考试的全部学生的考试题干成绩
            List<ExportEnterpriseExamineeScoreVo> enterpriseExamineeScoreVos = getExportEnterpriseExamineeSubjectScoreVos(queryEnterpriseExamineeGradeVo);
            ProgressManager.updateProgressCurrent(50, "查询表格内容完成");

            //5：设置总成绩 、学历、性别
            bulidEducationAndSex(enterpriseExamineeScoreVos);
            ProgressManager.updateProgressCurrent(60, "设置总成绩 、学历、性别完成");

            List<ExportEnterpriseExamineeSubjectGradeScoreVo> tempSubjectGradeScoreVos = new ArrayList<>(subjectList.size());
            for (ExportEnterpriseExamineeSubjectGradeScoreVo subjectGradeScoreVo : subjectList) {
                if (StringUtils.isEmpty(subjectGradeScoreVo.getSubjectId()) || !subjectGradeScoreVo.getSubjectId().equals(queryEnterpriseExamineeGradeVo.getSubjectId())) {
                    continue;
                }
                tempSubjectGradeScoreVos.add(subjectGradeScoreVo);
            }
            XSSFWorkbook xssfWorkbook = EnterpriseExamineeInfoExportUtil.getExamineeSinglSubjectXSSFWorkbook(enterpriseExamineeScoreVos, tempSubjectGradeScoreVos, queryEnterpriseExamineeGradeVo.getSheetName());
            ProgressManager.updateProgressCurrent(70, "生成Excel文件完成");

            dbfUrl = enterpriseExamineeInfoExportUtil.exportExcelV2(xssfWorkbook, queryEnterpriseExamineeGradeVo.getFileName());
            ProgressManager.updateProgressCurrent(80, "华为云文件上传完成");
        } catch (Exception e) {
            log.error("# 23、上传{}文件异常", queryEnterpriseExamineeGradeVo.getFileName(), e);
        }

        if (StringUtils.isEmpty(dbfUrl)) {
            BusinessLogicException.throwException(52293106, "文件生成失败");
        }
        ProgressManager.finish(dbfUrl);
    }


    private List<ExportEnterpriseExamineeScoreVo> getExportEnterpriseExamineeScoreVos(QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo) {
        if (null != queryEnterpriseExamineeGradeVo.getExamineeIds() && queryEnterpriseExamineeGradeVo.getExamineeIds().length > 0) {
            Map<String, Object> examineeParms = new HashMap<>();
            examineeParms.put("deptIds", queryEnterpriseExamineeGradeVo.getDeptIds());
            examineeParms.put("examineeIds", queryEnterpriseExamineeGradeVo.getExamineeIds());
            examineeParms.put("examId", queryEnterpriseExamineeGradeVo.getExamId());
            examineeParms.put("qualifiedStatus", queryEnterpriseExamineeGradeVo.getQualifiedStatus());
            examineeParms.put("archivedStatus", queryEnterpriseExamineeGradeVo.getArchivedStatus());
            examineeParms.put("examineeName", queryEnterpriseExamineeGradeVo.getExamineeName());
            examineeParms.put("subjectId", queryEnterpriseExamineeGradeVo.getSubjectId());
            List<EnterpriseExamineeExamGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseSubjectExamineeByParms(examineeParms);
            //总成绩 key examineeId
            Map<String, List<EnterpriseExamineeExamGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().filter(e -> StringUtils.isEmpty(e.getStemId())).collect(Collectors.groupingBy(c -> c.getExamineeId()));
            return getExportEnterpriseExamineeScoreVos(subjectGradeMap, CommonEnums.EXAM_MERGE_TYPE_1.getCode());
        } else {
            Map<String, Object> examineeParms = new HashMap<>();
            examineeParms.put("deptIds", queryEnterpriseExamineeGradeVo.getDeptIds());
            examineeParms.put("examId", queryEnterpriseExamineeGradeVo.getExamId());
            examineeParms.put("qualifiedStatus", queryEnterpriseExamineeGradeVo.getQualifiedStatus());
            examineeParms.put("archivedStatus", queryEnterpriseExamineeGradeVo.getArchivedStatus());
            examineeParms.put("examineeName", queryEnterpriseExamineeGradeVo.getExamineeName());
            examineeParms.put("subjectId", queryEnterpriseExamineeGradeVo.getSubjectId());
            List<EnterpriseExamineeExamGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseSubjectExamineeByParms(examineeParms);
            //总成绩 key examineeId
            Map<String, List<EnterpriseExamineeExamGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().filter(e -> StringUtils.isEmpty(e.getStemId())).collect(Collectors.groupingBy(c -> c.getExamineeId()));
            return getExportEnterpriseExamineeScoreVos(subjectGradeMap, CommonEnums.EXAM_MERGE_TYPE_1.getCode());
        }
    }


    private List<ExportEnterpriseExamineeScoreVo> getExportEnterpriseExamineeSubjectScoreVos(QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo) {
        if (null != queryEnterpriseExamineeGradeVo.getExamineeIds() && queryEnterpriseExamineeGradeVo.getExamineeIds().length > 0) {
            Map<String, Object> examineeParms = new HashMap<>();
            examineeParms.put("deptIds", queryEnterpriseExamineeGradeVo.getDeptIds());
            examineeParms.put("examineeIds", queryEnterpriseExamineeGradeVo.getExamineeIds());
            examineeParms.put("examId", queryEnterpriseExamineeGradeVo.getExamId());
            examineeParms.put("qualifiedStatus", queryEnterpriseExamineeGradeVo.getQualifiedStatus());
            examineeParms.put("regionName", queryEnterpriseExamineeGradeVo.getRegionName());
            examineeParms.put("archivedStatus", queryEnterpriseExamineeGradeVo.getArchivedStatus());
            examineeParms.put("examineeName", queryEnterpriseExamineeGradeVo.getExamineeName());
            examineeParms.put("subjectId", queryEnterpriseExamineeGradeVo.getSubjectId());
            List<EnterpriseExamineeExamGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.selectSubjectEnterpriseExamineeByParms(examineeParms);
            //总成绩 key examineeId
            Map<String, List<EnterpriseExamineeExamGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().filter(e -> StringUtils.isEmpty(e.getStemId())).collect(Collectors.groupingBy(c -> c.getExamineeId()));
            return getExportEnterpriseExamineeScoreVos(subjectGradeMap, CommonEnums.EXAM_MERGE_TYPE_1.getCode());
        } else {
            Map<String, Object> examineeParms = new HashMap<>();
            examineeParms.put("deptIds", queryEnterpriseExamineeGradeVo.getDeptIds());
            examineeParms.put("examId", queryEnterpriseExamineeGradeVo.getExamId());
            examineeParms.put("qualifiedStatus", queryEnterpriseExamineeGradeVo.getQualifiedStatus());
            examineeParms.put("regionName", queryEnterpriseExamineeGradeVo.getRegionName());
            examineeParms.put("archivedStatus", queryEnterpriseExamineeGradeVo.getArchivedStatus());
            examineeParms.put("examineeName", queryEnterpriseExamineeGradeVo.getExamineeName());
            examineeParms.put("subjectId", queryEnterpriseExamineeGradeVo.getSubjectId());
            List<EnterpriseExamineeExamGradeVo> enterpriseExamineeSubjectGradeVos = enterpriseExamineeSubjectGradeMapper.selectSubjectEnterpriseExamineeByParms(examineeParms);
            //总成绩 key examineeId
            Map<String, List<EnterpriseExamineeExamGradeVo>> subjectGradeMap = enterpriseExamineeSubjectGradeVos.stream().filter(e -> StringUtils.isEmpty(e.getStemId())).collect(Collectors.groupingBy(c -> c.getExamineeId()));
            return getExportEnterpriseExamineeScoreVos(subjectGradeMap, CommonEnums.EXAM_MERGE_TYPE_1.getCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshExamExamineeQualified(List<String> relationExamIds, String examId) {
        log.info("执行考试组refreshExamExamineeQualified开始...");
        // 判断考试是否存在
        ExamInfo examInfo = examInfoMapper.selectExamInfoById(examId);
        if (examInfo == null) {
            log.info("执行考试组refreshExamExamineeQualified考试id不存在...");
            return;
        }
        //合并科目
        if (CommonEnums.EXAM_MERGE_TYPE_1.getCode().equals(String.valueOf(examInfo.getMergeType()))) {
            enterpriseExamineeInfoService.refreshEnterpriseExamineeQualified(examId);
        } else {
            Map<String, Object> parms = new HashMap<>();
            parms.put("relationId", examInfo.getId());
            List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
            List<String> tempRelationExamIds = examInfoVos.stream().map(ExamInfoVo::getId).collect(Collectors.toList());
            //查询分页考生的所有科目
            List<EnterpriseScoreLineSaveParam> scoreLineSettings = enterpriseExamScoreLineSettingService.getScoreLineList(examId, null, null);
            Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(EnterpriseScoreLineSaveParam::getDimension));
            List<EnterpriseScoreLineSaveParam> examScoreLineSettings = scoreLineMap.get(CommonEnums.SCORE_LINE_DIMENSION_2.getCode());
            //设置分数线 单科
            Map<String, List<ScoreLineItem>> examSngleScoreLineItemMap = getSngleScoreLineItemMap(examScoreLineSettings);
            //设置分数线 复合
            Map<String, List<ScoreLineItem>> examCompositeScoreLineItemMap = getCompositeScoreLineItemMap(examScoreLineSettings);
            //区间分数线
            List<ScoreLineItem> examRegionScoreLineItemList = getRegionScoreLineItems(examScoreLineSettings);

            executeQualifiedStatus(examSngleScoreLineItemMap, examCompositeScoreLineItemMap, tempRelationExamIds);
            // 如果区间分数线不为空，设置了区间分数线，更新考试组区间名称
            if (CollUtil.isNotEmpty(examRegionScoreLineItemList)) {
                executeRegionname(examRegionScoreLineItemList, tempRelationExamIds);
            }

        }

        log.info("执行考试组refreshExamExamineeQualified结束...");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshEnterpriseExamineeQualified(String examId, String examineeId) {
        //考试组(查询考试组设置的分数线，更新考试组的合格状态)
        ExamInfo examInfo = examInfoMapper.selectExamInfoById(examId);
        if (null == examInfo || StringUtils.isEmpty(examInfo.getRelationId())) {
            return;
        }
        ExamInfo groupExamInfo = examInfoMapper.selectExamInfoById(examInfo.getRelationId());
        //合并考试
        if (!CommonEnums.EXAM_MERGE_TYPE_0.getCode().equals(String.valueOf(groupExamInfo.getMergeType()))) {
            return;
        }
        EnterpriseExamineeInfo enterpriseExamineeInfo = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoById(examineeId);
        if (null == enterpriseExamineeInfo || !enterpriseExamineeInfo.getExamId().equals(examId)) {
            return;
        }
        Map<String, String> tempMap = getGroupQualifiedStatusAndRegionName(groupExamInfo.getId(), enterpriseExamineeInfo.getIdcard(), enterpriseExamineeInfo.getName());

//        EnterpriseExamineeInfo enterpriseExamineeInfoParam = new EnterpriseExamineeInfo();
//        enterpriseExamineeInfoParam.setIdcard(enterpriseExamineeInfo.getIdcard());
//        enterpriseExamineeInfoParam.setName(enterpriseExamineeInfo.getName());
//        enterpriseExamineeInfoParam.setExamId();
//        List<EnterpriseExamineeInfo> enterpriseExamineeInfos = enterpriseExamineeInfoMapper.selectEnterpriseExamineeInfoList(enterpriseExamineeInfoParam);
//        if(CollectionUtils.isEmpty(enterpriseExamineeInfos)){
//            return;
//        }
        List<String> ids = Arrays.asList(tempMap.get("examineeIds").split(","));

        enterpriseExamineeInfoMapper.updateGroupQualifiedStatusAndRegionNameByIds(tempMap.get("qualifiedStatus"), tempMap.get("regionname"), ids.toArray(new String[ids.size()]));
    }

    @Override
    public Map<String, String> getGroupQualifiedStatusAndRegionName(String examId, String idCard, String examineeName) {
        Map<String, String> retMap = new HashMap<>(2);
        //查询分页考生的所有科目
        List<EnterpriseScoreLineSaveParam> scoreLineSettings = enterpriseExamScoreLineSettingService.getScoreLineList(examId, null, null);
        if (CollectionUtils.isEmpty(scoreLineSettings)) {
            retMap.put("regionname", CommonEnums.QUALIFIED_STATUS_D.getCode());
            retMap.put("qualifiedStatus", CommonEnums.QUALIFIED_STATUS_D.getCode());
        }
        Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getDimension()));
        List<EnterpriseScoreLineSaveParam> examScoreLineSettings = scoreLineMap.get(CommonEnums.SCORE_LINE_DIMENSION_2.getCode());
        //设置分数线 单科
        Map<String, List<ScoreLineItem>> examSngleScoreLineItemMap = getSngleScoreLineItemMap(examScoreLineSettings);
        //设置分数线 复合
        Map<String, List<ScoreLineItem>> examCompositeScoreLineItemMap = getCompositeScoreLineItemMap(examScoreLineSettings);
        //区间分数线
        List<ScoreLineItem> examRegionScoreLineItemList = getRegionScoreLineItems(examScoreLineSettings);
        //查询出考生在考试组下所以考试成绩
        Map<String, Object> parms = new HashMap<>();
        parms.put("relationId", examId);
        List<ExamInfoVo> examInfoVos = examInfoMapper.selectEnterpriseExamInfoByParms(parms);
        List<String> relationExamIds = examInfoVos.stream().map(item -> item.getId()).collect(Collectors.toList());
        Map<String, Object> examineeParms = new HashMap<>();
        examineeParms.put("examIds", relationExamIds.toArray(new String[relationExamIds.size()]));
        examineeParms.put("idCard", idCard);
        examineeParms.put("examineeName", examineeName);
        List<EnterpriseExamineeExamGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeByParms(examineeParms);
        //处理科目合格业务
        String qualifiedStatus = getExamQualifiedStatus(examSngleScoreLineItemMap, examCompositeScoreLineItemMap, gradeVos);
        //未设置分数线考试成绩返回为""
        if (CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(qualifiedStatus)) {
            retMap.put("qualifiedStatus", CommonEnums.QUALIFIED_STATUS_Y.getCode());
        } else if (CommonEnums.QUALIFIED_STATUS_N.getCode().equals(qualifiedStatus)) {
            retMap.put("qualifiedStatus", CommonEnums.QUALIFIED_STATUS_N.getCode());
        } else {
            retMap.put("qualifiedStatus", CommonEnums.QUALIFIED_STATUS_D.getCode());

        }

        //处理考试区间业务逻辑

        String regionName = getExamRegionName(examRegionScoreLineItemList, gradeVos);
        retMap.put("regionname", regionName);
        retMap.put("examineeIds", gradeVos.stream().distinct().map(e -> e.getExamineeId()).collect(Collectors.joining(",")));

        return retMap;
    }

    @Override
    public void updateExamExamineeQualified(List<String> examIds) {
        enterpriseExamineeInfoMapper.updateGroupRegionnameAndQualifiedStatus("", "", examIds.toArray(new String[examIds.size()]));
    }

    /**
     * 单科分数线Map
     *
     * @param scoreLineSettings
     * @return
     */

    private Map<String, List<ScoreLineItem>> getSngleScoreLineItemMap(List<EnterpriseScoreLineSaveParam> scoreLineSettings) {
        Map<String, List<ScoreLineItem>> sngleScoreLineItemMap = null;
        List<ScoreLineItem> sngleScoreLineItems = new ArrayList<>(4);
        if (CollectionUtils.isNotEmpty(scoreLineSettings)) {
            //分数线类型为单分组
            Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getType()));
            //根据单科分组
            if (CollectionUtils.isNotEmpty(scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_0.getCode()))) {
                for (EnterpriseScoreLineSaveParam lineSaveParam : scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_0.getCode())) {
                    sngleScoreLineItems.addAll(lineSaveParam.getScoreLineItems());
                }
                sngleScoreLineItemMap = sngleScoreLineItems.stream().collect(Collectors.groupingBy(c -> c.getExamId()));
            }


        }
        return sngleScoreLineItemMap;
    }

    /**
     * 复合分数线Map
     *
     * @param scoreLineSettings
     * @return
     */
    private Map<String, List<ScoreLineItem>> getCompositeScoreLineItemMap(List<EnterpriseScoreLineSaveParam> scoreLineSettings) {
        Map<String, List<ScoreLineItem>> compositeScoreLineItemMap = null;
        List<ScoreLineItem> compositeScoreLineItems = new ArrayList<>(4);
        if (CollectionUtils.isNotEmpty(scoreLineSettings)) {
            //分数线类型为单分组
            Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getType()));

            //根据复合分组
            if (CollectionUtils.isNotEmpty(scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_1.getCode()))) {
                for (EnterpriseScoreLineSaveParam lineSaveParam : scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_1.getCode())) {
                    compositeScoreLineItems.addAll(lineSaveParam.getScoreLineItems());
                }
                compositeScoreLineItemMap = compositeScoreLineItems.stream().collect(Collectors.groupingBy(c -> c.getSettingId()));

            }

        }
        return compositeScoreLineItemMap;
    }


    /**
     * 区间分数线Map
     *
     * @param scoreLineSettings
     * @return
     */
    private List<ScoreLineItem> getRegionScoreLineItems(List<EnterpriseScoreLineSaveParam> scoreLineSettings) {
        List<ScoreLineItem> compositeScoreLineItems = null;
        if (CollectionUtils.isNotEmpty(scoreLineSettings)) {
            //分数线类型为单分组
            Map<String, List<EnterpriseScoreLineSaveParam>> scoreLineMap = scoreLineSettings.stream().collect(Collectors.groupingBy(c -> c.getType()));
            compositeScoreLineItems = new ArrayList<>(scoreLineSettings.size());
            //根据区间分组
            if (CollectionUtils.isEmpty(scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_2.getCode()))) {
                return compositeScoreLineItems;
            }
            for (EnterpriseScoreLineSaveParam lineSaveParam : scoreLineMap.get(CommonEnums.SCORE_LINE_TYPE_2.getCode())) {
                compositeScoreLineItems.addAll(lineSaveParam.getScoreLineItems());
            }
        }
        return compositeScoreLineItems;
    }


    /**
     * 执行更新考试合格操作
     *
     * @param sngleScoreLineItemMap
     * @param compositeScoreLineItemMap
     */
    private void executeQualifiedStatus(Map<String, List<ScoreLineItem>> sngleScoreLineItemMap, Map<String, List<ScoreLineItem>> compositeScoreLineItemMap,
                                        List<String> relationExamIds) {
        Map<String, Object> examineeParms = new HashMap<>();
        examineeParms.put("examIds", relationExamIds.toArray(new String[relationExamIds.size()]));
        List<EnterpriseExamineeExamGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeByParms(examineeParms);
//        List<EnterpriseExamineeSubjectGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectExamineeSubjectGradeByExamIds();
        List<String> ids = new ArrayList<>();
        List<String> unids = new ArrayList<>();
        List<String> dids = new ArrayList<>();
        //处理考试合格业务逻辑
        Map<String, List<EnterpriseExamineeExamGradeVo>> gradeMap = gradeVos.stream().collect(Collectors.groupingBy(e -> e.getIdCard() + e.getName()));
        //处理科目合格业务
        for (String key : gradeMap.keySet()) {
            String qualifiedStatus = getExamQualifiedStatus(sngleScoreLineItemMap, compositeScoreLineItemMap, gradeMap.get(key));
            //未设置分数线考试成绩返回为""
            if (CommonEnums.QUALIFIED_STATUS_Y.getCode().equals(qualifiedStatus)) {
                for (EnterpriseExamineeExamGradeVo enterpriseExamineeExamGradeVo : gradeMap.get(key)) {
                    ids.add(enterpriseExamineeExamGradeVo.getExamineeId());
                }

            } else if (CommonEnums.QUALIFIED_STATUS_N.getCode().equals(qualifiedStatus)) {
                for (EnterpriseExamineeExamGradeVo enterpriseExamineeExamGradeVo : gradeMap.get(key)) {
                    unids.add(enterpriseExamineeExamGradeVo.getExamineeId());
                }
            } else {
                for (EnterpriseExamineeExamGradeVo enterpriseExamineeExamGradeVo : gradeMap.get(key)) {
                    dids.add(enterpriseExamineeExamGradeVo.getExamineeId());
                }
            }
        }


        //合格
        if (CollectionUtils.isNotEmpty(ids)) {
            enterpriseExamineeInfoMapper.updateGroupQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_Y.getCode(), ids.toArray(new String[ids.size()]));
        }
        //不合格
        if (CollectionUtils.isNotEmpty(unids)) {
            enterpriseExamineeInfoMapper.updateGroupQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_N.getCode(), unids.toArray(new String[unids.size()]));

        }

        if (CollectionUtils.isNotEmpty(dids)) {
            enterpriseExamineeInfoMapper.updateGroupQualifiedStatusByIds(CommonEnums.QUALIFIED_STATUS_D.getCode(), dids.toArray(new String[unids.size()]));

        }

    }


    /**
     * 执行更新考试区间操作
     *
     * @param examRegionScoreLineItemList
     */
    private void executeRegionname(List<ScoreLineItem> examRegionScoreLineItemList, List<String> relationExamIds) {


//        List<EnterpriseExamineeSubjectGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectExamineeSubjectGradeByExamIds(relationExamIds.toArray(new String[relationExamIds.size()]));
        Map<String, Object> examineeParms = new HashMap<>();
        examineeParms.put("examIds", relationExamIds.toArray(new String[relationExamIds.size()]));
        List<EnterpriseExamineeExamGradeVo> gradeVos = enterpriseExamineeSubjectGradeMapper.selectEnterpriseExamineeByParms(examineeParms);

        Map<String, List<EnterpriseExamineeExamGradeVo>> examineeSubjectGradeMap = gradeVos.stream().collect(Collectors.groupingBy(c -> c.getExamineeId()));

        List<EnterpriseExamineeSubjectGradeVo> subjectGradeVos = new ArrayList<>(examineeSubjectGradeMap.size());
        //处理考试区间业务逻辑
        for (String key : examineeSubjectGradeMap.keySet()) {
            String eegionName = getExamRegionName(examRegionScoreLineItemList, examineeSubjectGradeMap.get(key));
            EnterpriseExamineeSubjectGradeVo vo = new EnterpriseExamineeSubjectGradeVo();
            vo.setRegionName(eegionName);
            vo.setExamineeId(key);
            subjectGradeVos.add(vo);
        }

        Map<String, List<EnterpriseExamineeSubjectGradeVo>> examineeMap = subjectGradeVos.stream().collect(Collectors.groupingBy(c -> c.getRegionName()));
        for (String key : examineeMap.keySet()) {
            List<EnterpriseExamineeSubjectGradeVo> examinees = examineeMap.get(key);
            if (CollectionUtils.isEmpty(examinees)) {
                continue;
            }
            Set<String> ids = examinees.stream().map(EnterpriseExamineeSubjectGradeVo -> EnterpriseExamineeSubjectGradeVo.getExamineeId()).collect(Collectors.toSet());
            enterpriseExamineeInfoMapper.updateGroupRegionnameByIds(key, ids.toArray(new String[ids.size()]));
        }

    }

    /**
     * 考生总成绩合格设置
     *
     * @param regionScoreLineItemList 设置分数线 区间
     * @param allGradeList            考试所以的科目
     */
    private String getExamRegionName(List<ScoreLineItem> regionScoreLineItemList, List<EnterpriseExamineeExamGradeVo> allGradeList) {
        if (CollectionUtils.isEmpty(regionScoreLineItemList)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        if (CollectionUtils.isEmpty(allGradeList)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        //所以子考试分数
        //总得分
        BigDecimal totalScore = allGradeList.stream().map(EnterpriseExamineeExamGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String, BigDecimal> scoreMap = new HashMap<>(1);
        scoreMap.put(allGradeList.get(0).getExamId(), totalScore);
        //区间分数线 -- 找出复合未合格的直接返回
        Set<String> examIds = regionScoreLineItemList.stream().map(s -> s.getExamId()).collect(Collectors.toSet());
        BigDecimal tempScore = BigDecimal.ZERO;
        for (String sid : examIds) {
            //求和考生成绩
            if (null == scoreMap.get(sid)) {
                continue;
            }
            tempScore = tempScore.add(scoreMap.get(sid));

        }
        //按子考试分组，只需要取任意一组科目的区间。设置分数区间分数线时都存一样的，所以随机取一组即可
        Map<String, List<ScoreLineItem>> regionScoreLineItemMap = regionScoreLineItemList.stream().collect(Collectors.groupingBy(c -> c.getExamId()));
        String firstKey = regionScoreLineItemMap.keySet().stream().findFirst().get();
        List<ScoreLineItem> items = regionScoreLineItemMap.get(firstKey);
        if (CollectionUtils.isEmpty(items)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        for (ScoreLineItem item : items) {
            if (tempScore.compareTo(new BigDecimal(item.getRegionStartScore())) > -1
                    && tempScore.compareTo(new BigDecimal(item.getRegionEndScore())) < 0) {
                return item.getRegionName();
            }
        }

//        for (Map.Entry entry : regionScoreLineItemMap.entrySet()) {
//            //找出包含区间子考试
//            List<ScoreLineItem> items = regionScoreLineItemMap.get(entry.getKey());
//            if (CollectionUtils.isEmpty(items)) {
//                break;
//            }
//            for (ScoreLineItem item : items) {
//                if (tempScore.compareTo(new BigDecimal(item.getRegionStartScore())) > -1
//                        && tempScore.compareTo(new BigDecimal(item.getRegionEndScore())) < 0) {
//                    return item.getRegionName();
//                }
//            }
//            break;
//        }
        return CommonEnums.QUALIFIED_STATUS_D.getCode();

    }


    /**
     * 考生总成绩合格设置
     *
     * @param sngleScoreLineItemMap     设置分数线 单科
     * @param compositeScoreLineItemMap 设置分数线 复合
     * @param allSubjectGradeList       考试所以的科目
     */
    private String getExamQualifiedStatus(Map<String, List<ScoreLineItem>> sngleScoreLineItemMap
            , Map<String, List<ScoreLineItem>> compositeScoreLineItemMap, List<EnterpriseExamineeExamGradeVo> allSubjectGradeList) {
        if (MapUtils.isEmpty(sngleScoreLineItemMap) && MapUtils.isEmpty(compositeScoreLineItemMap)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        if (CollectionUtils.isEmpty(allSubjectGradeList)) {
            return CommonEnums.QUALIFIED_STATUS_D.getCode();
        }
        //单科分数线 找出单科未合格的直接返回
        if (MapUtils.isNotEmpty(sngleScoreLineItemMap)) {

            Map<String, List<EnterpriseExamineeExamGradeVo>> gradeMap = allSubjectGradeList.stream().collect(Collectors.groupingBy(e -> e.getExamId()));
            //考生是否考了已全部科目，没考则直接不合格
            if (sngleScoreLineItemMap.keySet().size() > gradeMap.size()) {
                return CommonEnums.QUALIFIED_STATUS_N.getCode();
            }


            for (String key : sngleScoreLineItemMap.keySet()) {
                BigDecimal totalScore = gradeMap.get(key).stream().map(EnterpriseExamineeExamGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);

                List<ScoreLineItem> items = sngleScoreLineItemMap.get(key);
                for (ScoreLineItem item : items) {
                    if (CommonEnums.COMPARISON_TYPE_1.getCode().equals(item.getComparisonType()) && StringUtils.isNotEmpty(item.getScore())
                            && totalScore.compareTo(new BigDecimal(item.getScore())) > -1) {
                        continue;
                    } else if (CommonEnums.COMPARISON_TYPE_0.getCode().equals(item.getComparisonType()) && StringUtils.isNotEmpty(item.getScore())
                            && totalScore.compareTo(new BigDecimal(item.getScore())) > 0) {
                        continue;
                    } else {
                        return CommonEnums.QUALIFIED_STATUS_N.getCode();
                    }
                }
            }
        }
        //复合分数线 -- 找出复合未合格的直接返回
        if (MapUtils.isNotEmpty(compositeScoreLineItemMap)) {
            //总得分
            BigDecimal totalScore = allSubjectGradeList.stream().map(EnterpriseExamineeExamGradeVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);
            Map<String, BigDecimal> scoreMap = new HashMap<>(1);
            scoreMap.put(allSubjectGradeList.get(0).getExamId(), totalScore);
            for (String key : compositeScoreLineItemMap.keySet()) {
                //找出包含复合科目
                List<ScoreLineItem> items = compositeScoreLineItemMap.get(key);
                Set<String> examIds = items.stream().map(s -> s.getExamId()).collect(Collectors.toSet());
                BigDecimal tempScore = new BigDecimal("0");
                //求和考生复合成绩
                for (String sid : examIds) {
                    if (null == scoreMap.get(sid)) {
                        continue;
                    }
                    tempScore = tempScore.add(scoreMap.get(sid));
                }
                if (CommonEnums.COMPARISON_TYPE_1.getCode().equals(items.get(0).getComparisonType()) && StringUtils.isNotEmpty(items.get(0).getScore())
                        && tempScore.compareTo(new BigDecimal(items.get(0).getScore())) > -1) {
                    continue;
                } else if (CommonEnums.COMPARISON_TYPE_0.getCode().equals(items.get(0).getComparisonType()) && StringUtils.isNotEmpty(items.get(0).getScore())
                        && tempScore.compareTo(new BigDecimal(items.get(0).getScore())) > 0) {
                    continue;
                } else {
                    return CommonEnums.QUALIFIED_STATUS_N.getCode();
                }
            }
        }
        return CommonEnums.QUALIFIED_STATUS_Y.getCode();

    }
}
